<template>
  <el-container :style="{ height: containerHeight + 'px' }">

    <!-- 部门组织树 -->
    <el-aside v-show="leftTree" style="width:14%; padding: 20px 30px;background: #fff;border-right: 1px solid #dfe6ec;">
      <el-tree
        style="font-size: 14px"
        ref="leftTree"
        :data="deptList"
        node-key="id"
        :props="defaultProps"
        :default-expanded-keys="[0]"
        empty-text="暂无组织"
        :show-checkbox="false"
        :highlight-current="true"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
      >
        <div class="custom-tree-node" slot-scope="{ node, data }">
          <div>
            <!-- 没有子元素时显示的图标 (即是最后一层) -->
            <span v-if="data.lastNode">
              <i class="el-icon-document" style="color: #8c8c8c; margin-right: 3px" ></i>
            </span>
            <!-- 有子元素显示的图标 -->
            <span v-else @click.stop="openBtn(data)">
              <!-- 这里的展开的显示隐藏即是 [+] [-]-->
              <svg-icon v-if="data.open" icon-class="add-s" style="margin-right: 4px; font-size: 18px"/>
              <svg-icon v-else icon-class="sub-s" style="margin-right: 4px" />
            </span>
            <!-- 名称 -->
            <span>{{ node.label }}</span>
          </div>
        </div>
      </el-tree>
    </el-aside>

    <el-main>
      <el-row style="margin:20px 0px">
        <el-tooltip transition="none" effect="dark" :content="leftTree ? '关闭组织面板':'打开组织面板'" placement="top-start">
          <el-button plain style="float:left;" :icon="leftTree ? 'el-icon-d-arrow-left' : 'el-icon-d-arrow-right' " @click="leftTree = !leftTree"></el-button>
        </el-tooltip>
        <el-button style="float:left;margin-right:10px" icon="el-icon-plus" v-if="hasPerm('sys:user:add')" type="success" size="medium" @click="addUser()">新增</el-button>
        <my-Search :searchOption="searchType" @onSearch="getSearchContent"></my-Search>
        <el-upload
          v-if="hasPerm('sys:user:import')"
          action="#"
          :show-file-list="false"
          accept=".xls,.xlsx"
          :http-request="handleRequest"
          :before-upload="handleBeforeUpload"
          style="display:inline;margin-right:10px"
        >
          <el-button :loading="uploadLoading" type="warning" icon="el-icon-download" size="medium" >导入生成</el-button>
        </el-upload>
        <el-button :loading="downloadLoading" @click="handleDownload" :disabled="selectTableRowId.length<=0 && !downloadLoading" v-if="hasPerm('sys:user:export')" type="warning" icon="el-icon-upload2" size="medium" >导出数据</el-button>
        <el-button :disabled="selectTableRowId.length<=1" v-if="hasPerm('sys:user:deletebatch')" type="danger" icon="el-icon-delete-solid" size="medium" @click="deleteUserBatch">批量删除</el-button>
      </el-row>
      <!-- 用户表格 -->
      <el-table border stripe @selection-change="selectTable" :height="tableHeight" row-key="id" ref="userTableData" :data="userTableData" :default-sort = "{prop: 'nid', order: 'ascending'}">
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <el-table-column width="70px"  prop="avatar" align="center" label="头像">
          <!-- v-if="!leftTree" label="头像"-->
          <template slot-scope="scope">
           <el-avatar v-if="scope.row.avatar" size="large" :src="scope.row.avatar" fit="contain"></el-avatar>
           <el-avatar v-else icon="el-icon-user-solid"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column sortable prop="nid" align="center" label="学号/工号"></el-table-column>
        <el-table-column sortable prop="username" align="center" label="姓名"></el-table-column>
        <el-table-column
          width="90px"
          prop="sex"
          align="center"
          label="性别"
          :filters="[{text: '男', value: 1},{text: '女', value: 0},{text: '保密', value: null}]"
          :filter-method="sexFilterHandler"
          >
          <template slot-scope="scope">
            <el-tag size="normal" type="warning" v-if="scope.row.sex == '0'">女</el-tag>
            <el-tag size="normal" v-if="scope.row.sex == '1' ">男</el-tag>
            <el-tag size="normal" type="info" v-if="scope.row.sex !=0 && scope.row.sex != 1" >保密</el-tag>
          </template>
        </el-table-column>
        <el-table-column sortable width="90px" prop="birthdate" align="center" label="年龄">
          <template slot-scope="scope">{{scope.row.birthdate | getDateTime(false)}}</template>
        </el-table-column>
        <el-table-column sortable prop="nickname" align="center" label="昵称"></el-table-column>
        <el-table-column prop="phone" align="center" label="电话号码"></el-table-column>
        <el-table-column sortable prop="deptName" align="center" label="所属组织"></el-table-column>
        <el-table-column prop="loginTime" align="center" label="登录状况">
          <template slot-scope="scope">{{scope.row.loginTime | getDateTime(true)}}</template>
        </el-table-column>
        <el-table-column width="90px" prop="status" align="center" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="editUserStatus(scope.row.id)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column width="200px" align="center"  label="操作">
          <template slot-scope="scope">
            <el-button v-if="hasPerm('sys:user:edit')" type="primary" icon="el-icon-edit" size="small" @click="editUser(scope.row)" >编辑</el-button>
            <el-dropdown
              @command="(command)=>{handleCommand(command, scope.row)}"
              trigger="click"
              style="margin-left:6px"
              placement="bottom-start">
              <el-button size="small" type="warning">
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="hasPerm('sys:user:userrole')" command="giverole">分配角色</el-dropdown-item>
                <el-dropdown-item v-if="hasPerm('sys:user:resetpw')" command="resetpw">重置密码</el-dropdown-item>
                <el-dropdown-item v-if="hasPerm('sys:user:delete')" command="delete">删除用户</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区 -->
      <pagination
      ref="pagination"
      @pagination="getPagination"
      :total="parseInt(totalPage)"
      :page="parseInt(searchCondition.page)"
      :limit="parseInt(searchCondition.pageSize)"
      :pageSizes="paginationSize"
      ></pagination>

    </el-main>

    <!-- 新增或编辑弹框 -->
    <my-dialog
      :title="userDialog.title"
      :width="userDialog.width"
      :height="userDialog.height"
      :visible="userDialog.visible"
      @onClose="onClose"
      @onConfirm="onConfirm"
    >
      <div slot="content" style="margin: 0 30px">
        <el-form
          :model="userFormData"
          ref="userFormRef"
          :rules="rules"
          label-width="82px"
          size="small"
        >
        <el-row>
          <el-col :span="11">
            <el-row>
              <el-form-item prop="username" size="small" label="用户姓名">
                <el-input clearable v-model="userFormData.username"></el-input>
              </el-form-item>
            </el-row>
            <el-row v-if="!actionType">
              <el-form-item prop="password" size="small" label="用户密码">
                <el-input :type="passwordType" v-model="userFormData.password" />
                <span class="show-pwd" @click="showPwd(true)">
                  <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
                </span>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item prop="deptId" size="small" label="组织部门">
                <el-cascader
                  clearable
                  filterable
                  :show-all-levels="false"
                  placeholder="点击选择或输入搜索组织部门"
                  :key="userFormData.deptId"
                  v-model="userFormData.deptId"
                  :options="cascaderDeptList"
                  :props="cascaderProps"
                  style="min-width: 284px;"
                  @change="autoNid"
                >
                </el-cascader>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item prop="nickname" size="small" label="用户昵称">
                <el-input clearable v-model="userFormData.nickname"></el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item prop="phone" size="small" label="电话号码">
                <el-input clearable v-model="userFormData.phone"></el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item prop="email" size="small" label="电子邮箱">
                <el-input clearable v-model="userFormData.email"></el-input>
              </el-form-item>
            </el-row>
          </el-col>
          <el-col :span="12" :offset="1">
            <el-row>
              <el-col :span="20">
                <el-form-item prop="nid" size="small" label="学号/工号">
                  <el-input :placeholder="editNid ? '选择组织部门后可自动生成':''" clearable v-model="userFormData.nid" :disabled="editNid"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="3" :offset="1">
                <el-tooltip effect="dark" :content="editNid ? '手动编辑': actionType ? '自动修正' :'自动生成'" placement="right-start">
                  <el-button size="small" plain :icon="editNid ? 'el-icon-edit':'el-icon-magic-stick'" @click="editNid = !editNid"></el-button>
                </el-tooltip>
              </el-col>
            </el-row>
            <el-row v-if="!actionType">
              <el-form-item prop="confirmPassword" size="small" label="确认密码">
                <el-input :type="checkPasswordType" v-model="userFormData.confirmPassword" />
                  <span class="show-pwd" @click="showPwd(false)">
                    <svg-icon :icon-class="checkPasswordType === 'password' ? 'eye' : 'eye-open'" />
                  </span>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item prop="birthdate" size="small" label="出生日期">
                <el-date-picker default-value="2000-1-1" type="date" value-format="yyyy-MM-dd" placeholder="点击选择出生日期" v-model="userFormData.birthdate"></el-date-picker>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item prop="sex" size="small" label="用户性别">
                <el-radio-group v-model="userFormData.sex">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="0">女</el-radio>
                  <el-radio :label="null">保密</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item prop="height" size="small" label="身高(CM)">
                <el-input-number controls-position="right" v-model="userFormData.height" :min="54" :max="250"></el-input-number>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item prop="weight" size="small" label="体重(KG)">
                <el-input-number controls-position="right" v-model="userFormData.weight" :min="40" :max="130"></el-input-number>
              </el-form-item>
            </el-row>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item prop="hobbies" size="small" label="兴趣爱好">
            <el-select
              style="min-width: 530px;"
              filterable
              default-first-option
              v-model="userFormData.hobbies"
              multiple :multiple-limit="5"
              placeholder="点击选择或输入搜索兴趣爱好（最多五项）"
            >
              <el-option
                v-for="item in categories"
                :key="item.id"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="remark" size="small" label="用户介绍">
            <el-input
              type="textarea"
              maxlength="100"
              show-word-limit
              v-model="userFormData.remark"
              :rows="4"
              resize="none"
              placeholder="（限100字）"
            ></el-input>
          </el-form-item>
        </el-row>
        </el-form>
      </div>
    </my-dialog>

    <!-- 分配权限穿梭框 -->
    <my-dialog
      :title="userRoleDialog.title"
      :width="userRoleDialog.width"
      :height="userRoleDialog.height"
      :visible="userRoleDialog.visible"
      @onClose="onCloseTransfer"
      @onConfirm="onConfirmTransfer"
    >
      <div slot="content" style="margin: 0 30px">
        <el-transfer
        v-model="userRoleList"
        :data="roleList"
        filterable
        filter-placeholder="输入搜索角色"
        :props="{ key: 'id', label: 'roleName' }"
        :titles="['未分配角色', '已分配角色']" />
      </div>
    </my-dialog>

  </el-container>
</template>

<script>
import { getDeptListApi, getDeptByIdApi } from "@/api/department";
import { getRoleApi, getRoleListApi } from "@/api/role";
import { getCategoryApi } from "@/api/category";
import {
  getUserListApi,
  addUserApi,
  editUserApi,
  editUserStatusApi,
  deleteUserApi,
  deleteUserBatchApi,
  editUserRoleApi,
  addUserBatchApi,
  restUserPWApi
} from "@/api/user";
import myDialog from "@/components/MyDialog/index";
import mySearch from "@/components/MySearch/index";
import pagination from "@/components/Pagination/index";
export default {
  components: { myDialog, mySearch, pagination},
  data() {
    var confirmPassword = (rule, value, callback) => {
        if(value !== this.userFormData.password) {
            callback(new Error('两次输入密码不一致'));
        }else{
            callback();
        }
    };
    var checkPhone = (rule, value, callback) => {
        if(value){
            let rePhoneNum =  /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
            if(rePhoneNum.test(value)){
                callback();
            }else{
                callback(new Error('请输入正确的电话号码'));
            }
        }else{
            callback();
        }
    };
    var checkNid = (rule, value, callback) => {
        if(value){
            let reNum =  /^\d{8,10}$/;
            if(reNum.test(value)){
                callback();
            }else{
                callback(new Error('学号/工号应为8-10位的纯数字'));
            }
        }else{
            callback();
        }
    };
    return {
      //container高度
      containerHeight: 0,
      //表格高度
      tableHeight: 0,
      //左侧部门树是否显示
      leftTree: true,
      //树属性配置
      defaultProps: {
        children: "children",
        label: "deptName",
      },
      //左侧部门树数据域
      deptList: [],
      //用户表格信息
      userTableData:[],
      //被选中的行
      selectTableRowId: [],
      //查询条件
      searchCondition :{
        page: 1,
        pageSize: 10,
        id: this.$store.getters.userId,
        deptId: "",
        type: "",
        searchContent: ""
      },
      //分页容量
      paginationSize: [5,10,30,50,100,200],
      //筛选项
      searchType:[{label:"学号/工号",value:"0"},{label:"用户姓名",value:"1"},{label:"电话号码",value:"2"},{label:"用户昵称",value:"3"},],
      //查询返回 总记录数
      totalPage: 0,
      //true：编辑 flase :新增
      actionType: "",
      //true：自动生成学号 flase :手动编辑
      editNid: true,
      //新增或编辑弹框属性
      userDialog: {
        title: "",
        width: 900,
        height: 0,
        visible: false,
      },
      //运动类别
      categories: "",
      //新增或编辑表单数据域
      userFormData: {
        id: "",
        nid: "",
        username: "",
        nickname: "",
        sex: "",
        birthdate: "",
        height: "",
        weight: "",
        hobbies: "",
        remark: "",
        phone: "",
        email: "",
        checkEmail: "",
        password: "",
        checkPassword: "",
        confirmPassword: "",
        deptId: "",
        avatar: "",
        version:""
      },
      //检测邮箱是否更改
      preEmail:"",
      //新增或编辑表单验证规则
      rules: {
        nid: [
          { required: true, trigger: "blur", message: "请填写学号/工号" },
          { validator: checkNid, trigger: 'blur' }
        ],
        deptId: { required: true, trigger: "blur", message: "请选择组织部门" },
        username: { required: true, trigger: "blur", message: "请填写用户姓名" },
        password: { required: true, trigger: "blur", message: "请填写用户密码" },
        confirmPassword: { validator: confirmPassword, trigger: 'blur' },
        phone: [
          { required: true, trigger: "blur", message: "请填写电话号码" },
          { validator: checkPhone, trigger: 'blur' },
        ],
        birthdate: { required: true, trigger: "blur", message: "请选择出生日期" },
        email: [
          { required: true, trigger: "blur", message: "请填写电子邮箱" },
          { type: 'email', trigger: 'blur', message: '请输入正确的电子邮箱' }
        ],
      },
      passwordType: 'password',
      checkPasswordType: 'password',
      //联级选择数据
      cascaderDeptList: [],
      //组织联级选择配置
      cascaderProps:{
        emitPath: false,
        expandTrigger:'hover',
        value: "id",
        label: "deptName"
      },
      userRoleDialog: {
        title: "",
        width: 692,
        height: 340,
        visible: false,
      },
      //分配角色的用户Id
      editUid: "",
      //用户未拥有的角色
      roleList:[],
      //用户已拥有的角色
      userRoleList: [],
      //导出excel配置
      //是否正在导出
      downloadLoading: false,
      //导出文件名
      filename: "用户信息表",
      //是否正在导入
      uploadLoading: false,
    }
  },
  created() {
    this.getDeptList();
    this.getCategory().then(_=>{
      this.getUserList();
    })
  },
  mounted() {
    this.$nextTick(() => {
      this.containerHeight = window.innerHeight - 85;
      //有页码区就高度多-120
      this.tableHeight = window.innerHeight - 208 - 120;
    });
  },
  methods: {
    //获取左侧部门树数据
    async getDeptList() {
      let res = await getDeptListApi();
      if (res && res.code == 200) {
        this.cascaderDeptList = res.data;
        let copyList =[{children:[],id:0,deptName:"组织部门",open:false}];
        copyList[0].children = res.data;
        this.deptList = this.addOpen(copyList);
        // 无总树根
        // let copyList = res.data;
        // this.deptList = this.addOpen(copyList);
      }
    },
    //添加open、lastNode属性
    addOpen(list){
      list.forEach(item=>{
        if (item.children.length > 0) {
          if(item.id==0){
            item.open = false;
          }else{
            item.open = true;
          }
          item.lastNode = false;
          this.addOpen(item.children)
        }else{
          item.lastNode = true;
          delete item.children;
        }
      })
      return list;
    },
    //加减号图标点击事件
    openBtn(data) {
      data.open = !data.open;
      this.$refs.leftTree.store.nodesMap[data.id].expanded = !data.open;
    },
    //左侧部门树节点点击事件
    handleNodeClick(data) {
      this.searchCondition.deptId = data.id;
      this.getUserList();
    },
    //内容查询
    getSearchContent(val,type){
      this.searchCondition.searchContent = val;
      this.searchCondition.type = type;
      this.getUserList();
    },
    //分页查询getPagination
    getPagination(val){
      this.searchCondition.page = val.page;
      this.searchCondition.pageSize = val.limit;
      this.getUserList();
    },
    //获取运动类型
    async getCategory() {
      let res = await getCategoryApi();
      if(res && res.code == 200) {
        this.categories = res.data;
        // this.getUserList();
      }
    },
    //获取用户列表
    async getUserList(){
      let res = await getUserListApi(this.searchCondition);
      if( res && res.code==200) {
        this.totalPage = res.data.total;
        let copyList = res.data.records
        copyList.forEach(item=>{
          if(item.hobbies!=null) {
            //取现有全部类型
            let categoryIds = [];
            this.categories.forEach(item=>{
              categoryIds.push(item.id);
            })
            //用户现有类型
            let userHobbyIds = item.hobbies.split(",").map(Number);
            //全部类型与用户现有类型取交集，检查是否有类型失效
            item.hobbies = categoryIds.filter(item=>{
              return userHobbyIds.includes(item);
            })
          }
          this.getDeptName(item.deptId).then((res)=>{
            item.deptName = res.deptName;
          })
        })
        //延迟传输数据，让dom节点先渲染出来
        setTimeout(()=>{
          this.userTableData = copyList;
        },200)
      }
    },
    //遍历组织获取对应的组织名称
    async getDeptName(id){
      let res = await getDeptByIdApi({id:id});
      if(res.code==200){
        return res.data;
      }
    },
    //性别筛选
    sexFilterHandler(value, row, column){
      const property = column['property'];
      return row[property] === value;
    },
    //显示密码
    showPwd(flag) {
      if(flag){
        if (this.passwordType === 'password') {
          this.passwordType = ''
        } else {
          this.passwordType = 'password'
        }
      }else{
        if (this.checkPasswordType === 'password') {
          this.checkPasswordType = ''
        } else {
          this.checkPasswordType= 'password'
        }
      }
    },
    //修改用户状态
    async editUserStatus(value){
      let res = await editUserStatusApi(value);
      if (res && res.code == 200) {
        //刷新列表
        this.getUserList();
        this.$message.success(res.msg);
      }
    },
    //密码强度判断
    checkPassword(psw){
      var lv = 0; //初始化提示消息为空
      if (psw.match(/[a-z]/g)) { lv++; } //验证是否包含小写字母
      if (psw.match(/[A-Z]/g)) { lv++; } //验证是否包含大写字母
      if (psw.match(/[0-9]/g)) { lv++; } // 验证是否包含数字
      if (psw.match(/[!@#$%^&*?._-]/g)) { lv++; } //验证是否包含字符
      return lv;
    },
    //新增或编辑确认
    onConfirm() {
      this.$refs.userFormRef.validate(async (valid) => {
        if (valid) {
          let res = null;
          if(this.userFormData.hobbies != null){
            if(this.userFormData.hobbies !=''){
              this.userFormData.hobbies = this.userFormData.hobbies.toString();
            }else{
              this.userFormData.hobbies = null;
            }
          }
          if (this.actionType) {
            //邮箱更改了自动解绑
            if(this.userFormData.email!=this.preEmail){
              this.userFormData.checkEmail = 0;
            }
            //编辑
            res = await editUserApi(this.userFormData).catch(_=>{
              this.$message.error("数据库已存在该账号，请重试！");
            });
          } else {
            this.userFormData.checkPassword = this.checkPassword(this.userFormData.password);
            //新增
            res = await addUserApi(this.userFormData).catch(_=>{
              this.$message.error("数据库已存在该账号，请重试！");
            });
          }
          if (res && res.code == 200) {
            //刷新列表
            this.getUserList();
            this.userDialog.visible = false;
            this.$message.success(res.msg);
          }
        }
      });
    },
    //新增或编辑取消
    onClose() {
      this.userDialog.visible = false;
      this.editNid = true;
    },
    //新增按钮
    addUser() {
      this.$resetForm("userFormRef", this.userFormData);
      this.userDialog.title = "新增用户";
      this.userDialog.height = 466;
      this.userDialog.visible = true;
      this.actionType = false;
    },
    //编辑按钮
    editUser(row) {
      this.$resetForm("userFormRef", this.userFormData);
      //把当前要编辑的数据复制到数据域，tApi给表单回显
      this.$objCoppy(row, this.userFormData);
      //检测邮箱是否更改
      this.preEmail = this.userFormData.email;
      //设置编辑的标识
      this.actionType = true;
      //设置弹框属性
      this.userDialog.title = "编辑角色";
      this.userDialog.height = 416;
      this.userDialog.visible = true;
    },
    //自动生成学号/工号
    async autoNid(){
      if(this.userFormData.deptId!=null){
        let id = this.userFormData.deptId
        if(this.editNid){
          let deptcode = [];
          deptcode.unshift(await this.countSameDept(id))
          let pidList = this.findTreePrevChainById(this.deptList[0].children,id)
          pidList.forEach(item=>{
            deptcode.unshift(item.deptCode)
          })
          if(this.actionType){
            deptcode.unshift(this.userFormData.nid.substr(0,2))
          }else{
            deptcode.unshift(new Date().getFullYear().toString().substr(2,2));
          }
          this.userFormData.nid = '';
          this.userFormData.nid = deptcode.join('')
        }
      }
    },
    //根据id找到所有父级
    findTreePrevChainById(arr1, id){
      let temp = []
      const dp = (arr, id) => {
        for(let i = 0; i < arr.length; i++){
          const item = arr[i]
          if(item.id === id){
            temp.push(item)
            dp(arr1, item.pid)
            break
          }else{
            if(item.children){
              dp(item.children, id)
            }
          }
        }
      }
      dp(arr1, id)
      return temp
    },
    //查找相同组织的人数
    async countSameDept(id){
      let count = 0;
      let parm = {
        page: 1,
        pageSize: 100,
        id: 1,
        deptId: id
      }
      let res = await getUserListApi(parm);
      if(res && res.code == 200){
        count = res.data.total;
        if(!this.actionType){
          count++
          if(count<10){
            return  "0"+count;
          }else{
            return count.toString();
          }
        }else{
          return this.userFormData.nid.substr(this.userFormData.nid.length-2,2)
        }
      }
    },
    //更多下拉菜单
    handleCommand(command,row) {
      switch (command) {
        case 'giverole':
          this.giveUserRole(row)
        break;
        case 'resetpw':
          this.resetUserPW(row)
        break;
        case 'delete':
          this.deleteUser(row)
        break;
      }
    },
    //重置密码为当前首字母大写电子邮箱域名+学号后四位+电话号码4-7位
    async resetUserPW(row){
      let confirm = await this.$myconfirm("确定重置用户【"+row.username+"】的密码吗？");
      if (confirm) {
        let front = row.email.substr(row.email.lastIndexOf('@') + 1).split(".")[0];
        let pwfront = front.charAt(0).toUpperCase() + front.slice(1);
        let pwmiddle = row.nid.substr(row.nid.length-4,4);
        let pwend = row.phone.substr(3,4);
        let newpw = pwfront+pwmiddle+pwend;
        let pwlv = this.checkPassword(newpw);
        let parm ={
          id: row.id,
          password: newpw,
          checkPassword: pwlv
        }
        let res = await restUserPWApi(parm);
        if (res && res.code == 200) {
          this.getUserList();
          this.$message.success(res.msg);
          // this.$message.success("重置的密码为："+newpw);
        }
      }
    },
    //获取当前登录用户的角色列表，除了管理员只能分配自身的角色
    async getRoleList() {
      let res = await getRoleListApi({uid:this.$store.getters.userId});
      if (res && res.code == 200) {
        this.roleList = res.data;
      }
    },
    //获取选中用户的角色id数组
    async getUserRoleList(uid){
      let res = await getRoleApi({uid:uid});
      if (res && res.code == 200) {
        res.data.forEach(item=>{
          this.userRoleList.push(item.rid)
        })
      }
    },
    //打开分配角色框
    giveUserRole(row){
      this.editUid = row.id;
      this.getRoleList();
      this.getUserRoleList(row.id);
      this.userRoleDialog.title = "为用户【"+row.username+"】分配角色";
      this.userRoleDialog.visible = true;
    },
    //关闭分配角色框
    onCloseTransfer(){
      this.userRoleDialog.visible = false;
      this.userRoleList=[];
      this.editUid = "";
    },
    //分配角色确认
    async onConfirmTransfer(){
      let parm = {
        uid : this.editUid,
        ridList : this.userRoleList
      }
      let res = await editUserRoleApi(parm)
        if (res && res.code == 200) {
          //刷新列表
          this.editUid = "";
          this.getUserList();
          this.onCloseTransfer();
          this.$message.success(res.msg);
        }
    },
    //删除按钮
    async deleteUser(row) {
      let confirm = await this.$myconfirm("确定删除用户【"+row.username+"】吗？");
      if (confirm) {
        let res = await deleteUserApi({id: row.id});
        if (res && res.code == 200) {
          // 检查最后一页是否只有一条数据
          if(this.searchCondition.pageSize ==1 || this.totalPage % this.searchCondition.pageSize ==1){
            this.searchCondition.page-=1;
          }
          //刷新列表
          this.getUserList();
          this.$message.success(res.msg);
        }
      }
    },
    //获取选择表格项
    selectTable(selection){
      this.selectTableRowId = [];
      selection.forEach(item=>{
        this.selectTableRowId.push(item.id);
      })
    },
    //批量删除
    async deleteUserBatch() {
      let confirm = await this.$myconfirm("此操作不可逆！确定删除这些用户吗？");
      if (confirm) {
        let deleteArray =this.selectTableRowId.toString();
        let res = await deleteUserBatchApi({ids:deleteArray});
        if(res && res.code == 200){
          if(this.totalPage % this.searchCondition.pageSize ==this.selectTableRowId.length){
            this.searchCondition.page-=1;
          }
          this.getUserList();
          this.$message.success(res.msg);
        }
      }
    },
    //导出数据
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['序号','学号/工号', '姓名', '所属组织', '性别', '出生日期', '身高(cm)', '体重(kg)', '电话号码', '电子邮箱']
        const filterVal = ['id','nid','username','deptName', 'sex', 'birthdate', 'height', 'weight', 'phone', 'email']
        const list = this.userTableData
        const data = this.formatJson(filterVal, list)

        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename+'_'+new Date().getTime(),
        })

        this.$refs.userTableData.clearSelection()
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    //导入数据
    async handleRequest({ file }){
      this.uploadLoading = true
      const formData = new FormData();
      formData.append('file',file);
      let res = await addUserBatchApi(formData).catch(_=>{
              this.$message.error("文件中某一账号在数据库中已存在，请核对后重试！");
            }).finally(this.uploadLoading = false)
      if(res&&res.code==200){
        this.$message.success(res.msg);
        this.getUserList();
      }
    },
    handleBeforeUpload(file){
      if (file.name.slice(-3) != "xls" && file.name.slice(-4) != "xlsx"){
        this.$message.error("文件格式错误，请导入格式为xls、xlxs的文件！");
        return false;
      }
      return true;
    },
  },
  watch: {
    editNid(val){
      if(val && this.userDialog.visible){
        this.autoNid()
      }
    }
  },
  filters: {
    getDateTime(val,flag){
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      month = (month > 9) ? month : ("0" + month);
      day = (day < 10) ? ("0" + day) : day;
      let today = year + "-" + month + "-" + day;
      let nowDate = Date.parse(today);
      let birthDate = Date.parse(val);
      let diffDate = Math.abs(nowDate-birthDate);
      if(flag){
        let days = Math.floor(diffDate / (1000*3600*24));
        let msg;
        if(days<1){
          msg = "今日活跃"
        }else if(days>1&&days<=3){
          msg = "最近活跃"
        }else if(days>3&&days<=7){
          msg = "最近登录"
        }else if(days>7&&days<=31){
          msg = "一周前登录"
        }else if(days>31&&days<=62){
          msg = "一个月前登录"
        }else if(days>62&&days<=93){
          msg = "两个月前登录"
        }else if(days>93&&days<=365){
          msg = "三个月前登录"
        }else if(days>365){
          msg = "一年前前登录"
        }else{
          msg = "未曾登录"
        }
        return msg;
      }else{
        if(Math.floor(diffDate / (1000*3600*24*365))>0){
          return Math.floor(diffDate / (1000*3600*24*365)) + "岁";
        }else{
          return "-";
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
  .el-aside ::v-deep .el-tree {
    // 将每一行的设置为相对定位 方便后面before after 使用绝对定位来固定位置
    .el-tree-node {
      position: relative;
      // padding-left: 10px;
    }
    // 子集像右偏移 给数线留出距离
    .el-tree-node__children {
      padding-left: 20px;
    }
    //这是竖线
    .el-tree-node :last-child:before {
      height: 40px;
    }
    .el-tree > .el-tree-node:before {
      border-left: none;
    }
    .el-tree > .el-tree-node:after {
      border-top: none;
    }
    //这自定义的线 的公共部分
    .el-tree-node:before,
    .el-tree-node:after {
      content: "";
      left: -4px;
      position: absolute;
      right: auto;
      border-width: 1px;
    }
    .tree :first-child .el-tree-node:before {
      border-left: none;
    }
    // 竖线
    .el-tree-node:before {
      border-left: 1px solid #d9d9d9;
      bottom: 0px;
      height: 100%;
      top: -25px;
      width: 1px;
    }
    //横线
    .el-tree-node:after {
      border-top: 1px solid #d9d9d9;
      height: 20px;
      top: 14px;
      width: 12px;
    }
    .el-tree-node__expand-icon.is-leaf {
      width: 8px;
    }
    //去掉elementui自带的展开按钮  一个向下的按钮,打开时向右
    .el-tree-node__content > .el-tree-node__expand-icon {
      display: none;
    }
    //每一行的高度
    .el-tree-node__content {
      line-height: 30px;
      height: 30px;
      padding-left: 10px !important;
    }
  }
  //去掉最上级的before  after 即是去电最上层的连接线
  .el-aside ::v-deep .el-tree > div {
    &::before {
      display: none;
    }
    &::after {
      display: none;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 1px;
    font-size: 16px;
    cursor: pointer;
    user-select: none;
  }
</style>
